<?php
/** 
 * Created by RisingSun. 
 * User: MarkSpace 
 * Date: 20231021
 * Time: 11:05 
 * 风控管理
 */
namespace app\product\controller;

use  Mscore\Core\Controller;
use  app\product\model\Duelcontrol as DuelcontrolModel;
use  app\product\model\Common as CommonModel;
use  Mscore\Core\Lib\ArrayMethod;
use  app\admin\model\Login as LoginModel;
use  Mscore\Core\Lang;

class DuelcontrolController extends Controller{

    private $model;
    private $login;
    private $error;
    private $success;
    private $language;
    private $key;
    private $keys;
    /**
     * 初始化自动连接方法
     * @param array $sysmod 
     * @param array $where 
    */
    public function __construct()  
    {    
        $this->login = (new LoginModel)->isAuth();
        if(isset($this->login['code'])&&$this->login['code']==401){
            echo json_encode($this->login);
            Header("Location:".config('server.login_url'));
            exit;
        }
        $this->key = config('duelcontrol.key');
        $this->keys = config('duelwebsocket.dueltrade');
        $this->model = new DuelcontrolModel;
        $this->language = isset($_COOKIE['language'])?$_COOKIE['language']:'default';
        Lang::init($this->language);
        $this->success=Lang::get('Success');
        $this->error=Lang::get('Error');
    }   

    /**
     * 运营列表
     * @param array $list 
     * @param array $where 
     */ 
    public function list(){  
        $post = post();
        switch (true) {
            case $post:
                $page = post('page',1);
                $limit = post('limit',10);
                $where = ' a.dels<1 ';
                if($this->login['info']['ranges']<1){
                    $where .= ' and a.aid = '.$this->login['info']['aid'];
                }
                if(post('title')){
                    $where .= ' and a.title like "%'.post('title').'%"';
                }
                if(post('username')){
                    $where .= ' and a.username like "%'.post('username').'%"';
                }
                $datalist = $this->model->list($where,$page,$limit);
                $data = [
                    "code" => 200,
                    "data" => $datalist['datalist'],
                    "count"=> $datalist['total'],
                    "msg" => 'ok'
                ];
                $this->echojson($data);
                break;
            default:
                $this->display('list.html');
                break;
        }
    }

    /**
     * 选择运营列表
     * @param array $checklist 
     * @param array $where 
     */ 
    public function checklist(){  
        //文章类
        $post = post();
        switch (true) {
            case $post:
                $page = post('page',1);
                $limit = post('limit',10);
                $where = ' a.dels<1 and a.relate<1 and a.aid<1';
                $datalist = $this->model->list($where,$page,$limit);
                $data = [
                    "code" => 200,
                    "data" => $datalist['datalist'],
                    "count"=> $datalist['total'],
                    "msg" => 'ok'
                ];
                $this->echojson($data);
                break;
            default:
                $this->display('checklist.html');
                break;
        }
    }

    /**
     * 添加
     * @param array $add 
     * @param array $where 
     */ 
    public function add(){
        $params = post();
        switch (true) {
            case $params: 
                $data = $this->model->save($params);
                switch ($data) {
                    case true:
                        logrecord('添加/修改当冲'.$params['title'].'风控:成功',$this->login['info']);
                        $this->echoJson($this->success);
                        break;
                    default:
                        logrecord('添加/修改当冲'.$params['title'].'风控:失败',$this->login['info']);
                        $this->echoJson($this->error);
                        break;
                } 
                break;
            default:
                if(get('id')){
                    $datainfo =$this->model->info(get('id'));
                    $datainfo['disk']=$this->model->disk('operate_id = '.get('id'));
                }
                $pro = (new CommonModel())->getDay('dels<1 and status<2','id,title,procode');
                $operate=(new CommonModel())->getBaseinfo('keyname="'.$this->key.'"','content');
                $operate=isset($operate['content'])?$operate['content']:[];
                //定义变量datainfo输出
                $datainfo['id']=isset($datainfo['id'])?$datainfo['id']:'';
                $datainfo['title']=isset($datainfo['title'])?$datainfo['title']:'';
                if($this->login['info']['grade']!='superadmin'){
                   $datainfo['aid']=isset($datainfo['aid'])?$datainfo['aid']:$this->login['info']['aid'];
                   $datainfo['username']=isset($datainfo['username'])?$datainfo['username']:$this->login['info']['username'];
                   $datainfo['auto']=isset($datainfo['auto'])?$datainfo['auto']:1;
                }else{
                   $datainfo['aid']=isset($datainfo['aid'])?$datainfo['aid']:0;
                   $datainfo['username']=isset($datainfo['username'])?$datainfo['username']:'';
                   $datainfo['auto']=isset($datainfo['auto'])?$datainfo['auto']:2;
                }
                $datainfo['proid']=isset($datainfo['proid'])?$datainfo['proid']:0;
                $datainfo['conuts']=isset($datainfo['conuts'])?$datainfo['conuts']:10;
                $datainfo['description']=isset($datainfo['description'])?$datainfo['description']:'';
                $datainfo['status']=isset($datainfo['status'])?$datainfo['status']:1;
                $datainfo['fixmoney']=isset($datainfo['fixmoney'])?$datainfo['fixmoney']:'500|1000|1500|2000';
                $datainfo['fixtime']=isset($datainfo['fixtime'])?$datainfo['fixtime']:'60|120|150|180';
                $datainfo['timetype'] = isset($operate['timetype'])?$operate['timetype']:1;
                if(isset($operate['fixtime'])&&$datainfo['timetype']==2){
                    $datainfo['fixtime']=isset($datainfo['fixtime'])?$datainfo['fixtime']:$operate['fixtime'];
                }
                $datainfo['language']=isset($datainfo['language'])?$datainfo['language']:'zh';
                $datainfo['disk']=isset($datainfo['disk'])?$datainfo['disk']:[];
                $datainfo['relate']=isset($datainfo['relate'])?$datainfo['relate']:0;
                $datainfo['relatename']=isset($datainfo['relatename'])?$datainfo['relatename']:'';
                $this->assign('datainfo',$datainfo);
                $this->assign('grade',$this->login['info']['grade']);
                $this->assign('pro',$pro);
                $this->display('add.html');
                break;
        }
    }

    /**
     * 删除
     * @param array $del 
     * @param array $where 
     */
    public function del(){
        $data=$this->model->del(post('id',false));
        switch ($data) {
            case true:
                $this->model->deldisk(' operate_id = '.post('id',false));
                logrecord('删除当冲风控id为：'.post('id',false).'的数据:成功',$this->login['info']);
                $this->echoJson($this->success);
                break;
            default:
                logrecord('删除当冲风控id为：'.post('id',false).'的数据:失败',$this->login['info']);
                $this->echoJson($this->error);
                break;
        } 
    }
    
    /**
     * 运营管控
     * @param array $controllist 
     * @param array $where 
     */ 
    public function controllist(){  
        //文章类
        $post = post();
        switch (true) {
            case $post:
                $page = post('page',1);
                $limit = post('limit',10);
                $where = ' a.dels<1 and a.status = 1 ';
                if($this->login['info']['ranges']<1){
                    $where .= ' and a.aid = '.$this->login['info']['aid'];
                }
                if(post('title')){
                    $where .= ' and a.title like "%'.post('title').'%"';
                }
                if(post('username')){
                    $where .= ' and a.username like "%'.post('username').'%"';
                }
                $datalist = $this->model->list($where,$page,$limit);
                $data = [
                    "code" => 200,
                    "data" => $datalist['datalist'],
                    "count"=> $datalist['total'],
                    "msg" => 'ok'
                ];
                $this->echojson($data);
                break;
            default:
                $this->display('clist.html');
                break;
        }
    }

    /**
     * 运营管控
     * @param array $cshow 
     * @param array $where 
    */ 
    public function cshow(){  
        $params = post();
        switch (true) {
            case $params:
                if($params['id']){
                    $where='operate_id='.$params['id']." and (createtime BETWEEN CONCAT(CURDATE(),' 00:00:00') AND CONCAT(CURDATE(),' 23:59:59'))";
                    $sum=$this->model->diskinfo($where,' count(id) as sum');
                    $params['conuts'] = intval($params['conuts']);
                    if(empty($params['conuts'])) {
                        $this->error['msg']='请设置场次';
                        $this->echoJson($this->error);
                    };
                    $max=floor((strtotime('23:59:00')-strtotime(date('H:i:00',time())))/60);
                    $sum= intval($sum['sum'])+$params['conuts'];
                    $info=$this->model->execRedis('get',[$this->key]);
                    $info=isset($info)&&!empty($info)?json_decode($info,true):[];
                    if($sum>intval($info['maxsn']) || $params['conuts']>$max){
                        $this->error['msg']='每天风控总条数不能大于'.$info['maxsn'].'条, 当前时间添加条数不能大于'.$max.'条。';
                        errlog('修改当冲运营管控:'.$this->error['msg'],$this->login['info']['username']);
                        $this->echoJson($this->error);
                    }
                } 
                $info = $this->model->savedisk($params);
                switch ($info) {
                    case true:
                        logrecord('修改当冲运营管控:成功',$this->login['info']);
                        $this->echoJson($this->success);
                        break;
                    default:
                        logrecord('修改当冲运营管控:失败',$this->login['info']);
                        $this->echoJson($this->error);
                        break;
                } 
                break;
            default:
                $info=$this->model->execRedis('get',[$this->key]);
                $info=json_decode($info,true);
                if(get('id')){
                    $datainfo =$this->model->info(get('id'));
                    $operateid=($datainfo['auto']==1)&&!empty($datainfo['relate'])?$datainfo['relate']:get('id');
                    $datainfo['opeid']=isset($operateid)?$operateid:get('id');
                    if(isset($info['acode'])&&!empty($info['acode'])){
                        $datainfo['rundisk']=$this->model->diskinfo('operate_id = '.$operateid.' and sn="'.$info['acode'].'"');
                    }
                    $datainfo['endtime']=isset($info['endtime'])&&!empty($info['endtime'])?$info['endtime']:0;
                }
                //定义变量datainfo输出
                $datainfo['id']=isset($datainfo['id'])?$datainfo['id']:'';

                $datainfo['aid']=isset($datainfo['aid'])?$datainfo['aid']:$this->login['info']['aid'];
                $datainfo['title']=isset($datainfo['title'])?$datainfo['title']:'';
                $datainfo['proid']=isset($datainfo['proid'])?$datainfo['proid']:0;
                $datainfo['aid']=isset($datainfo['aid'])?$datainfo['aid']:$this->login['info']['aid'];
                $datainfo['sn']=isset($info['acode'])?$info['acode']:'';
                $datainfo['conuts']=isset($datainfo['conuts'])?$datainfo['conuts']:10;
                $datainfo['description']=isset($datainfo['description'])?$datainfo['description']:'';
                $datainfo['status']=isset($datainfo['status'])?$datainfo['status']:1;
                $datainfo['language']=isset($datainfo['language'])?$datainfo['language']:'zh';
                $datainfo['disk']=isset($datainfo['disk'])?$datainfo['disk']:[];
                $datainfo['rundisk']=isset($datainfo['rundisk'])?$datainfo['rundisk']:['sn'=>$datainfo['sn']];
                $datainfo['run']=isset($datainfo['rundisk'])&&!empty($datainfo['rundisk'])?1:'';
                $datainfo['timetype']=isset($info['timetype'])?$info['timetype']:1;
                $this->assign('datainfo',$datainfo);
                $this->display('cshow.html');
                break;
        }
    }

    /**
     * 运营管控
     * @param array $cshow 
     * @param array $where 
    */ 
    public function disklist(){  
        $operateid = post('operateid');
        $page = post('page',1);
        $limit = post('limit',10);
        $datalist = $this->model->disklist(' operate_id = '.$operateid, $page, $limit);
        foreach ($datalist['datalist'] as $key => $value) {
            $where = 'sn="'.$value['sn'].'" and status<2';
            if($this->login['info']['ranges']<1){
                $where .= ' and pid = '.$this->login['info']['aid'];
            }
            $datalist['datalist'][$key]['ordernum'] = $this->model->countorder($where);
        }
        $data = [
            "code" => 200,
            "data" => $datalist['datalist'],
            "count"=> $datalist['total'],
            "msg" => 'ok'
        ];
        $this->echojson($data);
    }

    /**
     * 运营管控
     * @param array $cshow 
     * @param array $where 
    */ 
    public function showcontrol(){  
        $params = post();
        switch (true) {
            case $params:
                $data =$this->model->savediskinfo($params);
                switch ($data) {
                    case true:
                        logrecord('修改当冲运营管控:成功', $this->login['info']);
                        $this->echoJson($this->success);
                        break;
                    default:
                        logrecord('修改当冲运营管控:失败', $this->login['info']);
                        $this->echoJson($this->error);
                        break;
                } 
                break;
            default:
                if(get('id')){
                    $datainfo =$this->model->diskinfo('id='.get('id'));
                }
                $this->assign('datainfo',$datainfo);
                $this->display('showcontrol.html');
                break;
        }
    }
    /**
     * 獲取运营管控數據
     * @param array $cshow 
     * @param array $where 
    */ 
    public function getcontrol(){  
        $params = post();
        if($params['id']){
            $datainfo =$this->model->prodiskinfo('a.id='.$params['id'],'a.sn,b.proncode');
            $tradedata = $this->model->execRedis('hget',[$this->keys['tradekeys'],$datainfo['proncode']]);
            if(!empty($tradedata)){ $tradedata = json_decode($tradedata,true);}else{ $tradedata=[];}
            $order = $this->model->execRedis('hget',[$this->keys['order'],$datainfo['sn'].$datainfo['proncode']]);
            $order = !empty($order)?json_decode($order,true):[];$orderup=[];$orderdown=[];
            if(isset($order['buyup'])&&!empty($order['buyup'])){  $orderup = array_values($order['buyup']);}
            if(isset($order['buydown'])&&!empty($order['buydown'])){  $orderdown = array_values($order['buydown']);}
            $this->success['data']=[
                'trade'=>$tradedata,
                'orderup'=>$orderup,
                'orderdown'=>$orderdown
            ];
            $this->echoJson($this->success);
        }else{
            $this->echoJson($this->error);
        }
    }

    /**
     * 运营管控
     * @param array $cshow 
     * @param array $where 
    */ 
    public function showorder(){
        $post = post();
        switch (true) {
            case $post:
                $page = post('page',1);
                $limit = post('limit',10);
                if(get('id')){
                    $datainfo =$this->model->diskinfo('id='.get('id'));
                    if(isset($datainfo['sn'])&&!empty($datainfo['sn'])){
                        $where = ' a.sn = "'.$datainfo['sn'] .'" and a.status<2';
                        if($this->login['info']['ranges']<1){
                            $where .= ' and a.pid = '.$this->login['info']['aid'];
                        }
                        $datalist=$this->model->orderlist($where,$page,$limit);
                        if(!empty($datalist['datalist'])){
                            foreach ($datalist['datalist'] as $key => $value) {
                                if($datalist['datalist'][$key]['win']==0){
                                    $datalist['datalist'][$key]['win']=($datalist['datalist'][$key]['updown'] != $datainfo['win'])?1:2;
                                }
                            }
                        }
                        $nowdraw = $this->model->suminfo($where,' sum(a.money) as money, sum(a.sx_fee) as fee');
                        $up = $this->model->suminfo($where.' and a.updown=1',' sum(a.money) as money');
                        $down = $this->model->suminfo($where.' and a.updown=2',' sum(a.money) as money');
                        $nowdraw['money']=isset($nowdraw['money'])&&!empty($nowdraw['money'])?$nowdraw['money']:0;
                        $nowdraw['fee']=isset($nowdraw['fee'])&&!empty($nowdraw['fee'])?$nowdraw['fee']:0;
                        $nowdraw['up']=isset($up['money'])&&!empty($up['money'])?$up['money']:0;
                        $nowdraw['down']=isset($down['money'])&&!empty($down['money'])?$down['money']:0;
                    }
                    unset($datainfo);
                }
                $data = [
                    "code" => 200,
                    "data" => $datalist['datalist'],
                    "count"=> $datalist['total'],
                    "sum"=> $nowdraw,
                    "msg" => 'ok'
                ];
                $this->echojson($data);
                break;
            default:
                $this->display('showlist.html');
                break;
        }
    }

    /**
     * 删除
     * @param array $del 
     * @param array $where 
    */
    public function riskdel(){
        $data=$this->model->deldisk(' operate_id = '.post('id',false));
        switch ($data) {
            case true:
                logrecord('删除当冲风控记录:成功',$this->login['info']);
                $this->echoJson($this->success);
                break;
            default:
                logrecord('删除当冲风控记录:失败',$this->login['info']);
                $this->echoJson($this->error);
                break;
        } 
    }

    /**
     * 更新控制
     * @param array $del 
     * @param array $where 
    */
    public function operatesave(){
        $data=post();
        $id=$data['id']; unset($data['id']);
        switch ($id) {
            case true:
                $data=$this->model->operatesave('id = '.$id,$data);
                logrecord('更新控制:成功',$this->login['info']);
                $this->echoJson($this->success);
                break;
            default:
                logrecord('更新控制:失败',$this->login['info']);
                $this->echoJson($this->error);
                break;
        } 
    }

    /**
     * 运营管控删除风控
     * @param array $sdel 
     * @param array $where 
    */
    public function sdel(){
        $data=$this->model->del(post('id',false));
        switch ($data) {
            case true:
                $this->model->deldisk(' operate_id = '.post('id',false));
                logrecord('删除风控:成功',$this->login['info']);
                $this->echoJson($this->success);
                break;
            default:
                logrecord('删除风控:失败',$this->login['info']);
                $this->echoJson($this->error);
                break;
        } 
    }

    /**
     * 运营管控更改订单
     * @param array $del 
     * @param array $where 
    */
    public function setorder(){
        $post = post();
        switch (true) {
            case $post:
                if(isset($post['win'])&&!empty($post['win'])){
                    $this->model->setorder($post['id'],$post);
                    logrecord('风控单控订单:成功',$this->login['info']);
                    $this->echoJson($this->success);
                }else{
                    $this->echoJson($this->error);
                }
                break;
            default:
                $this->assign('id',get('id'));
                $this->display('setorder.html');
                break;
        } 
    }

    /**
     * 初始化控制
     * @param array $initcontrol 
     * @param array $where 
    */
    public function initcontrol(){
        $procode=(new CommonModel())->getDuelcontrol('aid=0','b.proncode');
        if(empty($procode)){$this->echoJson($this->error);}
        $procode = array_column($procode, 'proncode');
        $operate=(new CommonModel())->getBaseinfo('keyname="'.$this->key.'"','content');
        $control=config('duelcontrol');
        if(isset($control['duelcontrol'])){ unset($control['duelcontrol']);}
        $info=$this->model->execRedis('get',[$this->key]);
        $info=isset($info)&&!empty($info)?json_decode($info,true):[];
        switch (true) {
            case !empty($control)&&!empty($info):
                $minute = ceil((date('H')*60+date('i'))/($control['timelong']/60));
                $info['timelong']=$control['timelong'];
                $info['maxsn']=floor((24*60*60)/$control['timelong']);
                $info['sn'] = $minute;
                $info['fshow'] = isset($operate['fshow'])?$operate['fshow']:$control['fshow'];
                $info['acode']=date('Ymd',time()).str_pad($minute,$control['len'],'0',STR_PAD_LEFT);
                $info['backcode']=date('Ymd',time()).str_pad(($minute-1),$control['len'],'0',STR_PAD_LEFT);
                $info['fixmoney']=isset($operate['fixmoney'])?$operate['fixmoney']:$control['fixmoney'];
                $info['procode']=$procode;
                $info['settletime']=$control['settletime'];
                $info=$this->model->execRedis('set',[$this->key,json_encode($info)]);
                $this->model->cleardata();
                logrecord('初始化控制:成功',$this->login['info']);
                $this->echoJson($this->success);
                break;
            default:
                logrecord('初始化控制:失败,未启动程序',$this->login['info']);
                $this->echoJson($this->error);
                break;
        } 
    }

    /**
     * 用户信息
     * @param array $userinfo 
     * @param array $where 
     */ 
    public function rulelist(){
        $ruleinfo =$this->model->ruleinfo('id='.post('id'));
        $ruleinfo=!empty($ruleinfo['ids'])?explode(",", $ruleinfo['ids']):[];
        $total=count($ruleinfo);
        $page = post('page',1);
        $limit = post('limit',10);
        $rule = array_slice($ruleinfo,$limit*($page-1),$limit);
        foreach ($rule as $key => $value) {
            $rule[$key]=$this->model->info($value,'id,title,relate,relatename,createtime,status');
        }
        $rule = array_filter($rule);
        $data = [
            "code" => 200,
            "data" => $rule,
            "count"=> $total,
            "msg" => 'ok'
        ];
        $this->echojson($data);
    }

    /**
     * 自动化控制
     * @param array $autorule 
     * @param array $where 
    */
    public function autorule(){
        $params = post();
        switch (true) {
            case $params:
                if(!empty($params)){
                    $params['type']=isset($params['type'])?$params['type']:1;
                    if($params['type']==1){
                        $rule =$this->model->ruleinfo('id=1');
                        $params['ids']=$rule['ids'].','.$params['ids'];
                        $params['ids']=!empty($params['ids'])?array_unique(array_filter(explode(",", $params['ids']))):[];
                        $data=[
                            'ids'=>implode(',',$params['ids'])
                        ];
                    }else{
                        $data=[
                            'ids'=>''
                        ];
                    }
                    $this->model->rulesave($data);
                    if($params['type']==1){
                        foreach ($params['ids'] as $key => $value) {
                            $this->model->rulesaveop($value,$auto=1);
                        } 
                    }
                    $this->echojson($this->success);
                }
                $this->echojson($this->error);
                break;
            default:
                $datainfo =$this->model->ruleinfo('id=1');
                $datainfo['ids']=!empty($datainfo['ids'])?$datainfo['ids']:'';
                $datainfo['starttime']=!empty($datainfo['starttime'])?date('H:i:00',strtotime($datainfo['starttime'])):'07:00:00';
                $datainfo['endtime']=!empty($datainfo['endtime'])?date('H:i:00',strtotime($datainfo['endtime'])):'23:59:00';
                $this->assign('datainfo',$datainfo);
                $this->display('autorule.html');
                break;
        }
    }
    /**
     * 启动服务
     * @param array $editrule 
     * @param array $where 
     */ 
    public function editrule(){
        $params = post();
        if(!empty($params)){
            $params=[
                'starttime'=>!empty($params['starttime'])?date('H:i:00',strtotime($params['starttime'])):'07:00:00',
                'endtime'=>!empty($params['endtime'])?date('H:i:00',strtotime($params['endtime'])):'23:59:00'
            ];
            $this->model->rulesave($params);
            $this->echojson($this->success);
        }
        $this->echojson($this->error);
    }

    /**
     * 用户信息
     * @param array $delrule 
     * @param array $where 
     */ 
    public function delrule(){
        $ruleinfo =$this->model->ruleinfo('id=1');
        $rule=!empty($ruleinfo['ids'])?explode(",", $ruleinfo['ids']):[];
        $rule = array_diff($rule, [post('id')]);
        $params=[
            'id'=>1,
            'ids'=>implode(',', $rule)
        ];
        $status=$this->model->rulesave($params);
        if($status){
            $status=$this->model->rulesaveop(post('id'),2);
            $this->echojson($this->success);
        }
        $this->echojson($this->error);
    }

    /**
     * 账户列表
     * @param array $checkrule 
     * @param array $where 
     */ 
    public function checkrule(){
        $post = post();
        if ($post) {
            $page = post('page',1);
            $limit = post('limit',10);
            $where = ' a.dels<1 and a.aid<1 and a.status<2';
            if($this->login['info']['ranges']<1){
                $where .= ' and a.aid = '.$this->login['info']['aid'];
            }
            if(post('user_name')){
                $where .= ' and a.username like "%'.post('user_name').'%"';
            }
            if(post('nickname')){
                $where .= ' and a.title like "%'.post('nickname').'%"';
            }
            $datalist = $this->model->list($where,$page,$limit);
            $data = [
                "code" => 200,
                "data" => $datalist['datalist'],
                "count"=> $datalist['total'],
                "msg" => 'ok'
            ];
            $this->echojson($data);
        } else {
            $this->display('checkrule.html');
        }
    }

}
